
import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/user_info_request.dart';
import 'package:elephant_fish/model/user_info_entity.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'login_page.dart';

class FamilyCreatePage extends StatefulWidget {
  const FamilyCreatePage({Key key}) : super(key: key);

  @override
  _FamilyCreatePageState createState() => _FamilyCreatePageState();
}

class _FamilyCreatePageState extends State<FamilyCreatePage> {

  List<File> _images = [];
//  List<PickedFile> _images = [];
  TextEditingController nameController = TextEditingController();
  TextEditingController introduceController = TextEditingController();
  UserInfoEntity userInfoEntity;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getInitData();
  }

  @override
  Widget build(BuildContext context) {
    return
      Scaffold(
      backgroundColor: Color(0xff140c3d),
      appBar: AppBar(
        backgroundColor: Color(0xff140c3d),
        centerTitle: true,
        leading: GestureDetector(
          child: Icon(
            Icons.arrow_back_ios,
            size: SizeUtil.px(32),
            color: Color(0xfff3f3f3),
          ),
          onTap: () {
            Navigator.pop(context);
          },
        ),
        title: Text(
          '创建家族',
          style: TextStyle(fontSize: SizeUtil.px(32), color: Color(0xfff5f5f5)),
        ),
      ),
      body:
     SingleChildScrollView(
       child:  Column(
         children: [
           Container(
             width: double.infinity,
             height: 37.5,
             decoration: BoxDecoration(
               gradient: LinearGradient(
                 begin: Alignment.centerLeft,
                 end: Alignment.centerRight,
                 colors: [Color(0xfffe4d4e), Color(0xffff2d8f)],
               ),
             ),
             child: Align(
               alignment: Alignment.centerLeft,
               child: Padding(
                 padding: EdgeInsets.only(left: 18),
                 child: Text('以下信息均为必填项，为保证您的利益，请如实填写',style: TextStyle(color: Color(0xfff3f3f3),fontSize: 11.5),),
               ),
             ),
           ),
           SizedBox(height: 1,),
           Container(
             width: double.infinity,
             height: 129.5,
             color: Color(0xff2b244d),
             child: Column(
               children: [
                 SizedBox(height: 11.5,),
                 Row(
                   children: [
                     SizedBox(width: 18,),
                     Text('添加家族图片',style: TextStyle(color: Color(0xfff3f3f3),fontSize: 14),),
                     SizedBox(width: 8.5,),
                     Text('*此为家族头衔',style: TextStyle(color: Color(0xffe62d6c),fontSize: 11.5),),
                   ],
                 ),
                 SizedBox(height: 10.5,),
                 Padding(
                   padding: EdgeInsets.only(left: 18),
                   child: InkWell(
                     child: Center(
                         child: Container(
                           //加载网络图片
                           height: 70.0,
                           width: 70.0,
                           decoration: BoxDecoration(
                             color: Color(0xffd5d5d5),
                             borderRadius: BorderRadius.all(
                               Radius.circular(10),
                             ),
                           ),
                           child:  Wrap(
                             spacing: 5,
                             runSpacing: 5,
                             children: _generateImages(),
                           ),
                         )),
                     onTap: () async {
                       // var image = picker.getImage(source: ImageSource.gallery);
                       _pickImage();

                       // _imagePath = image;
                     },
                   ),
                 ),
               ],
             ),
           ),
           SizedBox(height: 10,),
           Container(
               width: double.infinity,
               height: 70,
               color: Color(0xff2b244d),
               child: Column(
                 children: [
                   Row(
                     children: [
                       SizedBox(width: 18,),
                       Text('家族名称',style: TextStyle(color: Color(0xfff3f3f3),fontSize: 14),),
                     ],
                   ),
                   TextField(
                       controller: nameController,
                       textAlign: TextAlign.center,
                       style: TextStyle(
                           fontSize: 13,
                           color: Color(0xfff3f3f3),
                           fontWeight: FontWeight.bold),
                       //输入框的样式
                       decoration: InputDecoration(
                         contentPadding:
                         EdgeInsets.only(left: 18, right: 18),
                         border: InputBorder.none,
                         hintText: '请填写你的家族名称',
                         hintStyle: TextStyle(
                           fontSize: 11.5,
                           color: Color(0xffa5a5a5),
                         ),
                       ))
                 ],
               )

           ),
           SizedBox(height: 10,),
           Container(
             width: double.infinity,
             height: 115,
             color: Color(0xff2b244d),
             child: Column(
               children: [
                 SizedBox(height: 10,),
                 Row(
                   children: [
                     SizedBox(width: 18,),
                     Text('家族简介',style: TextStyle(color: Color(0xfff3f3f3),fontSize: 14),),
                   ],
                 ),

                 TextField(
                     controller: introduceController,
                     textAlign: TextAlign.center,
                     style: TextStyle(
                         fontSize: 13,
                         color: Color(0xfff3f3f3),
                         fontWeight: FontWeight.bold),
                     //输入框的样式
                     decoration: InputDecoration(
                       contentPadding:
                       EdgeInsets.only(left: 18, right: 18),
                       border: InputBorder.none,
                       hintText: '请输入家族简介',
                       hintStyle: TextStyle(
                         fontSize: 11.5,
                         color: Color(0xffa5a5a5),
                       ),
                     ))


               ],
             ),
           ),
           SizedBox(height: 60,),
           InkWell(
             child: Container(
               width: 258.5,
               height: 36.5,
               decoration: BoxDecoration(
                 color: Color(0xffe62d6c),
                 borderRadius: BorderRadius.all(Radius.circular(21.5)),
               ),
               child: Center(
                 child:  Text('立即创建',style: TextStyle(color: Color(0xfff3f3f3),fontSize: 14),),
               ),
             ),
             onTap: (){
               createFamily();
             },
           )
         ],
       ),
     )
    );
  }


  createFamily() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    String name = nameController.text;
    String  introduction = introduceController.text;
    if(name == '' || introduction == "" || _images[0] == null){
      TxUtils.showToast('数据填写不完整', context);
    }else{
      FormData formData = FormData.fromMap({
        'name': name,
        'type': 2,
        'user_id': userInfoEntity.userId1,
        'introduction': introduction,
        'icon': await MultipartFile.fromFile(_images[0].path),
      });
      var dio = new Dio();
      dio.options.headers = {"usertoken": appToken};
      var response ;
      try{
        response = await dio.post("http://119.28.131.94:82/app/family/users/add", data: formData);
        var result = response.data;
        if (result['code'] == -1) {
          TxUtils.showErrorToast('登录失效，请重新登录', context);
          Navigator.pop(context);
          Navigator.of(context).push(MaterialPageRoute(
            builder: (context) {
              return LoginPage(
                arguments: {'loginCode': '-1'},
              );
            },
          ));
        } else if (result['code'] == 413) {
          TxUtils.showErrorToast('文件太大，无法上传', context);
        } else {
          TxUtils.showToast(result['data'], context);
          Navigator.pushNamed(context, '/index');
        }
      }catch(e){
        print(e);
        if(e.response.statusCode == 413){
          TxUtils.showErrorToast('文件太大，无法上传', context);
        }
      }
    }
  }


  Future getImage(bool isTakePhoto) async {
    Navigator.pop(context);
    var image;
    try {
      image = await ImagePicker.pickImage(
          source:isTakePhoto ? ImageSource.camera :ImageSource.gallery
      );
      if (image == null) {
        return;
      } else {
        setState(() {
          // _image = image;
          _images.add(image);
        });
      }
    } catch (e) {
      print("模拟器不支持相机！");
    }
  }

  ///底部弹框
  _pickImage() {
    showModalBottomSheet(context: context, builder: (context) =>
        Container(
          height: 160,
          child: Column(
            children: <Widget>[
              _takePhotoItem('拍照', true),
              _takePhotoItem('从相册选择', false),
            ],
          ),
        ));
  }
  _takePhotoItem(String title, bool isTakePhoto) {
    print(isTakePhoto);
    return GestureDetector(
      child: ListTile(
        leading: Icon(
          isTakePhoto ? Icons.camera_alt : Icons.photo_library,
        ),
        title: Text(title),
        onTap: () => getImage(isTakePhoto),
      ),
    );
  }

  /// 封装图片面板
  _generateImages() {
    return _images.map((file){
      return Stack(
        children: <Widget>[
          ClipRRect(
            //圆角效果
            borderRadius: BorderRadius.circular(SizeUtil.px(10)),
            child: Image.file(file,width: SizeUtil.px(140),height: SizeUtil.px(140),fit:BoxFit.fill),
          ),
          Positioned(
            right: 5,
            top: 5,
            child: GestureDetector(
              onTap: (){
                setState(() {
                  _images.remove(file);
                });
              },
              child: ClipOval(
                //圆角删除按钮
                child: Container(
                  padding: EdgeInsets.all(5),
                  decoration: BoxDecoration(color: Colors.black54),
                  child: Icon(Icons.close,size: 20,color: Colors.white,),
                ),
              ),
            ),
          ),
        ],
      );
    }).toList();
  }

  Future<void> getInitData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = UserInfoRequest();
    request.add('type', 2).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    }
    setState(() {
      userInfoEntity = UserInfoEntity.fromJson(
          new Map<String, dynamic>.from(result['data']));
    });
  }

}
